export default class BaseModel {
	private cacheKey : string;

	constructor(customKey : string = '') {
		// 默认使用类名作为缓存键
		this.cacheKey = customKey ?? this.constructor.name;
	}

	/**
	 * 缓存当前实例到本地
	 */
	public saveCache() : void {
		try {
			const json = JSON.stringify(this);
			uni.setStorageSync(this.cacheKey, json);
			console.log(`[缓存成功] ${this.cacheKey}`, json);
		} catch (error) {
			console.error(`[缓存失败] ${this.cacheKey}`, error);
		}
	}

	/**
	 * 加载缓存并返回当前类的实例（必须配合 fromJSON）
	 */
	public loadCache<T extends BaseModel>(this : T) : T | null {
		try {
			const raw = uni.getStorageSync(this.cacheKey);
			if (raw) {
				const json = JSON.parse(raw);
				const instance = new (this.constructor as any)(json);
				console.log(`[读取缓存] ${this.cacheKey}`, json);
				return instance;
			}
			return null;
		} catch (error) {
			console.error(`[读取缓存失败] ${this.cacheKey}`, error);
			return null;
		}
	}

	/**
	 * 清除缓存
	 */
	public clearCache() : void {
		try {
			uni.removeStorageSync(this.cacheKey);
			console.log(`[清除缓存] ${this.cacheKey}`);
		} catch (error) {
			console.error(`[清除缓存失败] ${this.cacheKey}`, error);
		}
	}
}